package cn.org.rookie.jeesdp.tools.runner;

import cn.org.rookie.jeesdp.core.properties.ConsulProperties;
import cn.org.rookie.jeesdp.core.properties.JeesdpProperties;
import lombok.extern.slf4j.Slf4j;
import org.h2.tools.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class ToolsApplicationRunner implements CommandLineRunner {
    @Autowired
    public JeesdpProperties properties;

    @Override
    public void run(String... args) {
        try {
            Server h2Server = Server.createTcpServer("-tcp", "-tcpAllowOthers", "-ifNotExists", "-tcpPort", "19092");
            h2Server.start();
            log.info("H2 Server is started at: {}", h2Server.getPort());
            Runtime runtime = Runtime.getRuntime();
            try {
                ConsulProperties consulProperties = properties.getConsul();
                if (consulProperties.isEnable()) {
                    Process process = runtime.exec(new String[]{String.format("%s/consul.exe", consulProperties.getDir()), "agent", String.format("-config-dir=%s", consulProperties.getConfigDir()), "-bootstrap-expect=1"});
                    runtime.addShutdownHook(new Thread(process::destroy));
                    new Thread(() -> {
                        try {
                            process.getInputStream().transferTo(System.out);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }).start();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
